import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/app/pctask/PcrwViewModel.dart';
import 'package:flutter_ahj_app/base/basewidget/HttpUtils/HttpBaseConst.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/utils/JUIKit/JText.dart';
import 'package:flutter_ahj_app/base/utils/StringUtils.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/mTopBar.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';
import 'package:flutter_ahj_app/base/widget/LoadingWidget.dart';
import 'package:flutter_ahj_app/base/widget/NoneData.dart';


class PCrwDetailView extends BaseStatefulWidget {
  final String hazardInvestigationTaskId;
  PCrwDetailView({this.hazardInvestigationTaskId});
  
  @override
  State<StatefulWidget> initState() {
    // TODO: implement initState
    // throw UnimplementedError();
    return PCrwDetailViewState();
  }
}

class PCrwDetailViewState extends BaseState<PcrwViewModel, PCrwDetailView> {
  ScrollController _scrollController;
  bool canLoadMore = true;
  List _datalist; //请求的数据列表
  int pageIndex = HttpBaseConst.pageIndex;

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        if (canLoadMore) _getData(1);
      }
    });
    Future.delayed(Duration.zero, () {
      _getData(0);
    });
  }

  @override
  Widget initWidget() {
    return Scaffold(
      backgroundColor: Color(0xfff4f5f6),
      appBar: MTopBar(
        elevation: 0,
        title: '排查任务执行详情',
      ).create(),
      body: _bodyView(),
    );
  }


  _bodyView() {
    return Column(
      children: [
        Expanded(
            child: Container(
              margin: EdgeInsets.fromLTRB(
                  Dimens.dimens16, Dimens.dimens16, Dimens.dimens16, Dimens.dimens16),
              child: _datalist == null
                  ? LoadingWidget()
                  : _datalist.length == 0
                  ? NoneData()
                  : RefreshIndicator(
                onRefresh: () => _getData(0),
                child: ListView.builder(
                  itemCount: _datalist.length,
                  controller: _scrollController,
                  physics: AlwaysScrollableScrollPhysics(),
                  itemBuilder: (BuildContext context, int index) {
                    return _item(index);
                  },
                ),
              ),
            ))
      ],
    );
  }

  _item(int index) {
    return Container(
      child: Column(
        children: [
          Container(
              padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
              decoration: BoxDecoration(
                color: SQColor.white,
                borderRadius: BorderRadius.circular(6),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Stack(
                        alignment: Alignment.center,
                        children: [
                          Image.asset(
                              "img/pxrw_zt_d.png",
                              width: 55,
                              height: Dimens.dimens20,
                              fit: BoxFit.fill),
                          JText(
                            StringUtils.getStr(_datalist[index]["taskExecuteStatusName"]),
                            color: SQColor.white,
                            fontSize: Dimens.dimens12,
                          ),
                        ],
                      ),
                    ],
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    child: JText(
                      StringUtils.getStr(_datalist[index]["riskPointName"]),
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    child: JText('场所/位置: ${StringUtils.getStr(_datalist[index]["districtName"])}', color: SQColor.black_999999),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    child: JText('管控责任单位：${StringUtils.getStr(_datalist[index]["orgName"])}', color: SQColor.black_999999),
                  ),
                  SizedBox(
                    height: Dimens.dimens16,
                  ),
                  _bottomView(index),
                  SizedBox(
                    height: Dimens.dimens16,
                  ),
                ],
              )),
          Container(
            height: 10,
            color: Color(0xfff6f6f6),
            width: double.infinity,
          ),
        ],
      ),
    );
  }

  _bottomView(int index) {
    return _ywc(index);
  }

  _ywc(int index) {
    return Container(
      padding: EdgeInsets.only(right: Dimens.dimens12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [

          InkWell(
            onTap: () {
              Navigator.pushNamed(context, '/PCrwSecDetailView', arguments: _datalist[index]["hazardInvestigationRiskPointId"].toString());
            },
            child: Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(right: 5),
              width: 88,
              height: 35,
              decoration: BoxDecoration(
                  color: Color(0xff165DFF),
                  borderRadius: BorderRadius.circular(16)),
              child: JText('查看详情', color: Colors.white),
            ),
          ),
        ],
      ),
    );
  }
  ///获得数据
  _getData(int type) async {
    if (type == 0) {
      //刷新
      pageIndex = HttpBaseConst.pageIndex;
    } else {
      //加载更多
      pageIndex += 1;
    }

    var map = {
      'size': HttpBaseConst.pageSize,
      'current': pageIndex,
      'hazardInvestigationTaskId': StringUtils.getStr(widget.hazardInvestigationTaskId)
    };
    print(widget.hazardInvestigationTaskId);
    viewModel.getfxdxxList(map);
    viewModel.getFxdxxDataStream().listen((result) {
      if (result['code'] == "0") {
        if (_datalist == null) _datalist = List();
        if (result == null ||
            result['data'] == null ||
            result['data']['total'] == 0 ||
            result['data']['records'] == null ||
            result['data']['records'].length == 0) {
          setState(() {
            if (type == 0) {
              //刷新
              _datalist.clear();
            } else {
              //加载更多
            }
          });
        } else {
          setState(() {
            if (type == 0) {
              //刷新
              _datalist.clear();
            } else {
              //加载更多
            }
            _datalist.addAll(result['data']['records']);
          });
        }
        setState(() {
          canLoadMore =
          _datalist.length == result['data']['total'] ? false : true;
        });
        print("******************length = ${_datalist.length}");
      } else {
        setState(() {
          _datalist = List();
        });
        ToastUtils.showToast(result['msg']);
      }
    });
  }

}
